package cn.itsource.basic.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

	@Override//进入controller之前，拦截
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception {
        // 1.获取 U-TOKEN 请求头里面的数据
        String token = req.getHeader("U-TOKEN");
        // 2.去redis里面 根据token 获取用户
        if (token!=null){
            Object o = redisTemplate.opsForValue().get(token);
            if (o!=null){
                // 3.不为空的情况 放行
                //刷新token的生命周期
                redisTemplate.opsForValue().set(token, o, 30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 4.其他 没有 U-TOKEN  或者没有获取到数据 都拦截
        //提示 {"success":false,"message":"noLogin"}
        //设置响应头
        resp.setContentType("application/json;charset=utf-8");

        PrintWriter writer = resp.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
	}

}
